<style>
.tree {
  /*margin-top: 42px;*/
  border: 1px solid #d7dde4;
  /* max-height: 600px; */
}
.editm {
  z-index: 20001;
}
.typeshow{
   z-index: 20002;
}
.upload-img {
  width: 100%;
}
</style>
<template>
<Row class="layout-content-body">
  <dtable :columns="columns" :dataAll="dataAll" :totals="total" 
  add delCheck check  @refresh="getall()" 
  @add="add" @del="del" @edit="edit" @delCheck="delCheck"
  @handelSelect="handelSelect" 
  :loading="loading"></dtable>
  <Modal title="产品信息" v-model="editData" :mask-closable="false" class-name="editm" @on-ok="asyncOK" @on-cancel="asyncCancel">
    <Form ref="editForm" :model="formItem" :label-width="80" :rules="ruleValidate">
      <Form-item label="名称" prop="Name">
        <Input v-model="formItem.Name" placeholder="请输入" @on-enter="asyncOK()"></Input>
      </Form-item>
      <Form-item label="产品类型" prop="Tname">
        <Input v-model="formItem.Tname" placeholder="请输入" @on-focus="SelectType()"></Input>
      </Form-item>
      <Form-item label="供应商" prop="Partner">
        <Select v-model="formItem.Partner" placeholder="请选择">
            <Option v-for="item  in partner" :value="item.Id" :key="item.Id">{{item.Name}}</Option>
        </Select>
      </Form-item>
      <Form-item label="型号" prop="Model">
        <Input v-model="formItem.Model" placeholder="请输入..." @on-enter="asyncOK()"></Input>
        </Input>
      </Form-item>
      <Form-item label="规格参数" prop="Spec">
        <Input v-model="formItem.Spec" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入" @on-enter="asyncOK()"></Input>
      </Form-item>
      <Form-item label="图片" prop="Img">
        <Row>
          <i-col span="10" v-if="formItem.Photo">
            <div class="demo-upload-list">
              <img :src="getPhoto(formItem.Photo)" class="upload-img">
            </div>
          </i-col>
          <i-col span="10">
            <Upload ref="upload" :on-success="handleSuccess" :format="['jpg','jpeg','png']" :max-size="2048" :on-format-error="handleFormatError" :on-exceeded-size="handleMaxSize" :on-remove="handleRemove" :before-upload="handleBeforeUpload" type="drag" :action="actionUrl">
              <div style="padding: 20px 0">
                <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                <p>点击或将文件拖拽到这里上传（仅限于mp4、flv格式文件）</p>
              </div>
            </Upload>
          </i-col>
        </Row>
      </Form-item>
      <Form-item label="采购成本" prop="Cost">
        <Input v-model.number="formItem.Cost" placeholder="请输入" @on-enter="asyncOK()"></Input>
      </Form-item>
      <Form-item label="售价" prop="Price">
        <Input v-model.number="formItem.Price" placeholder="请输入" @on-enter="asyncOK()"></Input>
      </Form-item>
      <Form-item label="控制售价" prop="ControlPrice">
        <Input v-model.number="formItem.ControlPrice" placeholder="请输入" @on-enter="asyncOK()"></Input>
      </Form-item>
      <Form-item label="说明" prop="Remark">
        <Input v-model="formItem.Remark" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入...">
        </Input>
      </Form-item>
    </Form>
  </Modal>
  <Modal title="上级类型" v-model="typeshow" @on-ok="typeok" class-name="typeshow" >
    <div span="4" class="tree">
      <Tree ref="Ptree" :data="typetree" @on-select-change="typeok"></Tree>
    </div>
  </Modal>
</Row>
</template>

<script>
import {
  SERVER_CPT_URL,
  V_ROOT
} from '@/api/config'
import {
  getData
} from '@/common/utils'
import {
   currency
} from '@/common/filter'
import dtable from '@/components/table/dtable.vue' //采用biztable
export default {
  data() {
    return {
      loading: false, //点击确定按钮时，确定按钮是否显示 loading 状态，开启则需手动设置visible来关闭对话框
      spinShow: false, //数据刷新遮罩层
      columns: [
        //多选框
        {
          title: '名称',
          key: 'Name',
          sortable: true
        },
        {
          title: '类型',
          key: 'Tname',
          sortable: true
        },
        {
          title: '型号',
          key: 'Model',
          sortable: true,
        },
        {
          title: '价格',
          key: 'Price',
          sortable: true,
          render: (h, params) => {
            return h('div', [
              h('strong', currency(params.row.Price,"￥"))
            ]);
          }
        },
        {
          title: '规格参数',
          key: 'Spec',
          sortable: false,
          width:380
        },
        {
          title: '图片',
          width:80,
          key: 'Photo',
          render: (h, params) => {
            return h('div', {
              attrs: {
                style: 'width: 40px;height: 40px;'
              },
            }, [
              h('img', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                attrs: {
                  src: this.getPhoto(params.row.Photo),
                  style: 'width: 40px;height: 40px;border-radius: 2px;'
                },
                style: {},
              }),
            ]);
          }
        },

      ], //表格样式
      dataAll: [], //表格数据来源
      dataShow: true, //是否显示表格数据查看表单
      editData: false, //显示编辑表单
      formItem: {}, //数据编辑表单
      ruleValidate: {
        Name: [{
          required: true,
          message: '名称不能为空',
          trigger: 'blur'
        }],
      }, //数据编辑表单验证规则
      addid: true, //true为修改模式，false为添加模式
      typetree: [],
      typeshow: false,
      partner: [],
      total: 0
    }
  },
  components: {
    dtable,
  },
  computed: {
    state() {
      return this.$store.state.app
    },
    actionUrl() {
      return SERVER_CPT_URL + '/upload/PhotoUpload?token=' + this.state.token
    },
    imgUrl() {
      if (!this.state.userInfo.Photo) {
        return "/static/img/default.jpg"
      } else {
        return V_ROOT + '/' + this.state.userInfo.Photo
      }
    }
  },
  watch: {},
  methods: {
    getPhoto(data) {
      if (!data) {
        return "/static/img/default.jpg"
      } else {
        return V_ROOT + '/' + data
      }
    },
    getall() {
      this.loading = true
      this.$api.getProd().then(res => {
        if (!res.error) {
          console.log(res.Data)
          this.dataAll = res.Data.tabledata
          this.typetree = res.Data.treedata
          this.partner = res.Data.partner
          if (this.dataAll) {
            this.total = (this.dataAll).length
          }
        } else {
          this.$Message.error(res.message)
        }
      })
      setTimeout(() => {
        this.loading = false;
      }, 500);
    },
    edit(index) {
      this.addid = true
      this.formItem = index
      this.editData = true
    },
    add() {
      this.addid = false
      this.$refs['editForm'].resetFields()
      this.editData = true
    },
    asyncOK() {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          if (this.addid) {
            this.$api.updateProd(this.formItem).then(res => {
              if (!res.error) {
                this.getall()
                this.$Message.success(res.message)
              } else {
                this.$Message.error(res.message, 4)
              }
            })
          } else if (!this.addid) {
            this.$api.addProd(this.formItem).then(res => {
              if (!res.error) {
                this.getall()
                this.$Message.success(res.message)
              } else {
                this.$Message.error(res.message, 4)
              }
            })
          }
          setTimeout(() => {
            this.editData = false;
          }, 1000);
        } else {
          this.$Message.error('表单验证失败!');
        }
      })
      this.editData = false
      this.$refs['editForm'].resetFields()

    },
    asyncCancel() {
      this.getall()
      this.$refs['editForm'].resetFields()
    },
    del(row) {
      this.$api.deleteProd(row).then(res => {
        if (!res.error) {
          this.getall()
          this.$Message.success(res.message)
        } else {
          this.$Message.error(res.message, 4)
        }
      })
    },
    delCheck(row) {
      this.$api.deleteProd(row).then(res => {
        if (!res.error) {
          this.getall()
          this.$Message.success(res.message)
        } else {
          this.$Message.error(res.message, 4)
        }
      })
    },
    SelectType() {
      this.typeshow = true
    },
    typeok() {
      // console.log(this.$refs.Ptree.getSelectedNodes()[0])
      this.formItem.ProdType = this.$refs.Ptree.getSelectedNodes()[0].id
      this.formItem.Tname = this.$refs.Ptree.getSelectedNodes()[0].title
      this.typeshow = false
    },
    ResCancel() {
      let row = {
        Url: this.formItem.Photo
      }
      if (this.isUpload) {
        this.$api.PhotoCancel(row).then(res => {
          // console.log("ok")
        })
      }
      this.$refs['upload'].clearFiles()
      this.$refs['formItem'].resetFields()
      this.isUpload = false
    },
    handleRemove(file) {
      this.ResCancel()
    },
    handleSuccess(res, file) {
      // console.log(res, file)
      this.isUpload = true
      this.formItem.Photo = res.jdata
    },
    handleFormatError(file) {
      this.$Notice.warning({
        title: '文件格式不正确',
        desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
      });
    },
    handleMaxSize(file) {
      this.$Notice.warning({
        title: '超出文件大小限制',
        desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
      });
    },
    handleBeforeUpload() {
      const check = this.$refs.upload.fileList < 2;
      if (!check) {
        this.$Notice.warning({
          title: '最多只能上传 1张图片。'
        });
      }
      return check;
    },
    handelSelect(row){
      this.$emit('handelSelect', row)
    }
  },
  mounted() {
    this.getall()
  }
}
</script>
